package com.archive.core.executor;

import com.archive.core.processor.ArchiveProcessor;
import com.archive.core.table.ArchiveColumn;
import com.archive.core.util.ArchiveUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

public class SameDBArchiveExecutor extends AbstractArchiveExecutor {

    public SameDBArchiveExecutor(ArchiveProcessor archiveProcessor) {
        super(archiveProcessor);
    }

    @Override
    public void checkArchiveTable(String tableName, String archiveTableName, Connection connection,
                                  Connection targetConnection) throws SQLException {
        checkArchiveTableSame(tableName, archiveTableName, connection);
    }

    @Override
    protected Statement getPreparedInsertStatement(Connection connection, Connection targetConnection, StringBuilder insertSql) throws SQLException {
        return connection.prepareStatement(insertSql.toString());
    }

    @Override
    public void checkTableColumn(String tableName, String archiveTableName) throws SQLException {
        Connection connection = null;
        Statement statement = null;
        Connection targetConnection = null;
        Statement targetStatement = null;
        try {
            String checkTable = "'" + tableName + "'" + ",'" + archiveTableName + "'";
            // 表结构修改所需时长未知，使用原始数据库连接，数据源获取的连接可能导致超时
            connection = getConnection();

            statement = connection.createStatement();
            Map<String, Map<String, ArchiveColumn>> tableColumns = getColumns(connection.getCatalog(), checkTable, statement);
            checkAndModifyColumns(tableName, archiveTableName, tableColumns, statement);
        } finally {
            ArchiveUtil.closeConnection(connection);
            ArchiveUtil.closeStatement(statement);
            ArchiveUtil.closeConnection(targetConnection);
            ArchiveUtil.closeStatement(targetStatement);
        }
    }

    @Override
    protected void appendPreparedInsertValue(Statement insertStatement, Object[] row, StringBuilder insertSql, int batchSize, Integer executeBatchSize, int clearPoint) throws SQLException {
        PreparedStatement ps = (PreparedStatement) insertStatement;
        int rowSize = row.length;
        for (int i = 0; i < rowSize; i++) {
            ps.setObject(i + 1, row[i]);
        }
        ps.addBatch();
    }

    @Override
    protected void appendPreparedRestInsertValue(Statement insertStatement, StringBuilder insertSql, int clearPoint) {

    }

}
